package springapp.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import springapp.service.RegistrationService;
import springapp.service.UserRegistrationForm;
import springapp.validator.UserRegistrationValidator;

@Controller
@SessionAttributes
@RequestMapping("/newuser.htm")
public class UserRegistrationValidController {
	
    private UserRegistrationValidator registrationValidation;
    private RegistrationService registrationService;

    @Autowired
    public void setRegistrationValidation(
    		UserRegistrationValidator registrationValidation) {
            this.registrationValidation = registrationValidation;
    }
    
	@RequestMapping(method = RequestMethod.POST)
    public String registerUser(@ModelAttribute("command")
                            UserRegistrationForm user, BindingResult result) {
 
		registrationValidation.validate(user, result);
        if (result.hasErrors()) {
                return "registeruser";
        }

        getRegistrationService().register(user);
        System.out.println("Registration. First Name:" + user.getFirstname() +
                    "Last Name:" + user.getLastname());
 
        return "registerusercompleted";
    }
 
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView showUserForm() {
 
        return new ModelAndView("registeruser", "command", new UserRegistrationForm());
    }

	public RegistrationService getRegistrationService() {
		return registrationService;
	}

	@Autowired
	public void setRegistrationService(RegistrationService registrationService) {
		this.registrationService = registrationService;
	}

}
